<template>
    <div>
      <!-- 面包屑导航区 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>管理员管理</el-breadcrumb-item>
        <el-breadcrumb-item>宿管列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图区 -->
      <el-card>
        <!-- 搜索与添加区域-->
        <el-row :gutter= "20">
          <el-col :span="9">
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList" >
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true">添加管理员</el-button>
          </el-col>
        </el-row>

        <!-- 管理员列表主体区域 -->
        <el-table :data="userList" border stripe  >
          <el-table-column align="center" type="index" label="#"></el-table-column>
          <el-table-column align="center" label="姓名" prop="userName"></el-table-column>
          <el-table-column align="center" label="性别">
            <template slot-scope="scope">
              <div v-if="scope.row.adminGender === 1">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-nan"></use>
                </svg>
              </div>
              <div v-else>
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-nv"></use>
                </svg>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="所属楼宇" prop="building.buildingNumber">
          </el-table-column>
          <el-table-column align="center" label="联系电话" prop="adminPhone"></el-table-column>
          <el-table-column align="center" label="角色">
            <template slot-scope="scope">
              {{scope.row.user.userType === 0 ? '系统管理员' : '宿舍管理员'}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态">
            <template slot-scope="scope">
              <el-switch  v-model="scope.row.adminStatus" :disabled="scope.row.user.userType === 0 ? true : false" @change="adminStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="140px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.adminId)"></el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDialog(scope.row)" ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>

      <!-- 添加用户的对话框 -->
      <el-dialog
        title="添加管理员"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed">
        <!-- 内容主体区 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="名称" prop="userName">
            <el-input v-model="addForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="电话号码" prop="adminPhone">
            <el-input v-model="addForm.adminPhone" onkeyup="value = value.replace(/[^\d]/g,'')"></el-input>
          </el-form-item>
          <el-form-item label="身份证号码" prop="adminIdentityCardNumber">
            <el-input v-model="addForm.adminIdentityCardNumber"></el-input>
          </el-form-item>
          <el-form-item label="管理级别" prop="userType">
            <el-select v-model="addForm.userType" placeholder="请选择">
              <el-option
                v-for="item in userTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

    <!-- 修改用户的对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="70%">
        <el-form ref="editFormRef" :model="editForm" :rules="addFormRules" label-width="100px">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="editForm.userName" disabled></el-input>
          </el-form-item>
          <el-form-item label="电话号码" prop="adminPhone">
            <el-input v-model="editForm.adminPhone"></el-input>
          </el-form-item>
          <el-form-item label="管理楼栋" prop="building">
              <el-select v-model="editForm.buildingId" :disabled="disabled" placeholder="请选择">
                <el-option value="-1" label="暂无"></el-option>
                <el-option
                  v-for="item in buildings"
                  :key="item.buildingId"
                  :label="item.buildingNumber"
                  :value="item.buildingId">
                </el-option>
              </el-select>
          </el-form-item>
          <el-form-item label="身份证号码" prop="adminIdentityCardNumber">
            <el-input v-model="editForm.adminIdentityCardNumber"></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="userPassword" clearable>
            <el-input v-model="editForm.user.userPassword"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"  @click="editAdminInfo">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>

    export default {
      data() {
        return {
          //用户列表
          userList: [],
          queryInfo: {
            query: '',
            //当前的页数
            pageNum: 1,
            //当前每页显示多少条数据
            pageSize: 10
          },
          //总记录数
          total: 0,
          //控制添加用户的对话框的显示/隐藏
          addDialogVisible: false,
          //控制修改用户的对话框的显示/隐藏
          editDialogVisible: false,
          //添加管理员的表单数据
          addForm: {
            userName: '',
            adminPhone: '',
            adminIdentityCardNumber: '',
            userType: '',
            adminStatus: true
          },
          // 修改用户信息
          editForm: {
            userName: '',
            adminPhone: '',
            buildingId: '',
            adminIdentityCardNumber: '',
            user: {
              userPassword: '',
              userType: ''
            }
          },
          //添加表单的验证规则对象
          addFormRules: {
            userName: [
              {required: true, message: '请输入管理员名称', trigger: 'blur'},
              {min: 2, max: 10, message: '用户名长度在2-10个字符', trigger: 'blur'}
            ],
            adminPhone: [
              {required: true, message: '请输入联系电话', trigger: 'blur'},
              {
                pattern: /^1[3|4|5|6|7|8|9]\d{9}$/,
                message: '请输入正确的电话号码', trigger: 'blur'
              }
            ],
            adminIdentityCardNumber: [
              {required: true, message: '请输入身份证号码', trigger: 'blur'},
              {
                pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
                message: '用户名长度在18个字符', trigger: 'blur'
              }
            ]
          },
          //修改用户表单的验证规则
          editFormRules: {

          },
          //楼宇管理
          disabled: false,
          buildings: [],
          //管理级别选项
          userType: '',
          userTypes: [{
            value: '0',
            label: '系统管理员'
          },{
            value: '1',
            label: '宿舍管理员'
          }]
        }
      },
      created() {
        this.getUserList()
      },
      methods: {
        //获取管理员列表数据
        async getUserList() {
          const { data: res } = await this.$axios.get(this.$http+'/adminManageController/findUserList',{
            params: this.queryInfo
          });
          if (res.code !== 200) return this.$message.error("获取管理员列表失败");
          this.userList = res.datas.userList;
          this.total = res.datas.total;
        },

        // 监听 pagesize 改变的事件
        handleSizeChange(newSize) {
          this.queryInfo.pageSize = newSize;
          //每次改变之后，重新获取数据
          this.getUserList()
        },

        //监听 页面值 改变的事件
        handleCurrentChange(newPage) {
          this.queryInfo.pageNum = newPage ;
          //每次改变之后，重新获取数据
          this.getUserList();
        },

        //监听switch开关状态的改变
        async adminStatusChange(userInfo){
          //发送网络通信
          await this.$axios({
           url: this.$http+`/adminManageController/updateUserStatus`,
           method: 'put',
           data: {
             adminId: userInfo.adminId,
             adminStatus: userInfo.adminStatus
           },
           headers: {
             'Content-Type': 'application/json'
           }
         }).then(res => {
           if (res.data.code === 200)
             this.$message.success("更新用户状态成功！");
           else if (res.data.code === 100)
             this.$message.error("更新用户状态失败！");
         }).catch(err => {
           this.$message.error("系统错误！")
         });
        },
        //监听添加管理员对话框的关闭,对内容进行清空
        addDialogClosed() {
          this.$refs.addFormRef.resetFields();
        },
        //添加新的管理员
        addUser() {
          //进行表单预验证
          this.$refs.addFormRef.validate(valid => {
            //如果valid 为 false ，直接退出
            if (!valid) return;

            //访问后台，进行用户名是否已存在验证
            this.$axios.get(this.$http+'/adminManageController/checkUserName?userName='+this.addForm.userName).then(res => {
              if (res.data.code === 200)
                return this.$message.warning("该用户名称已存在");
              else {
                //截取身份证后六位作为密码
                let password = "&" + this.$md5(this.addForm.adminIdentityCardNumber.substring(12));
                this.addForm.adminIdentityCardNumber += password;
                //发送添加用户网络请求
                this.$axios.post(this.$http+'/adminManageController/addAdmin', this.addForm, {
                  headers: {
                    'Content-Type': 'application/json'
                  }
                }).then(res => {
                  if (res.data.code === 200)
                    this.$message.success("添加用户成功！");
                  else if (res.data.code === 100)
                    this.$message.error("添加用户失败！");
                  //隐藏添加用户对话框
                  this.addDialogVisible = false;
                  //刷新宿管列表
                  this.getUserList();
                }).catch(err => {
                  console.log("异常错误",err)
                })
              }
            }).catch(err => {
              console.log("异常错误",err);
              return this.$message.warning("异常错误！")
            });
          })
        },

        //展示编辑用户的对话框
        async showEditDialog(id) {
          //发送网络请求，获取当前管理员的信息
          const { data: res} = await this.$axios.get(this.$http+`/adminManageController/getAdminInfo?id=`+id);
          if (res.code !== 200)
            return this.$message.error("查询用户信息失败");
          this.editForm = res.datas.adminInfo;
          this.buildings = res.datas.buildingList;
          // 系统管理员 不可管理 楼栋 --实现对select的禁用
          if (this.editForm.buildingId !== null){
            this.disabled = false;
          }else if (this.editForm.user.userType !== 0) {
            this.editForm.buildingId = '';
            this.disabled = false;
          }else {
            this.editForm.buildingId = '';
            this.disabled = true;
          }
          //显示编辑对话框
          this.editDialogVisible = true
        },

        //发送网络请求，修改用户数据
        async editAdminInfo() {
          this.buildingId = this.buildingId === '' ? -1 : this.buildingId;
          this.editForm.user.userPassword = this.$md5(this.editForm.user.userPassword);
          await this.$axios.put(this.$http+'/adminManageController/editAdminInfo', this.editForm,
            {
              headers: {
                'Content-Type': 'application/json;charset=utf-8'
              }
            }
          ).then(res => {
            if (res.data.code === 200)
            this.$message.success("修改用户信息成功！");
            else if (res.data.code === 100)
              this.$message.error("修改用户信息失败！");
            //隐藏添加用户对话框
            this.editDialogVisible = false;
            //刷新宿管列表
            this.getUserList();
          }).catch(err => {
            console.log("异常错误",err);
            return this.$message.warning("异常错误！")
          })
        },

        //发送网络请求，删除管理员用户所有信息
        async deleteDialog(admin) {
            //弹框是否确认删除
          const confirmResult = await this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).catch(err => err);
          if (confirmResult !== 'confirm'){ //如果返回字符串不是 confirm，则返回字符串为cancel
            return this.$message.info('已取消删除')
          }else { //发送网络请求
            await this.$axios.delete(this.$http+`/adminManageController/deleteAdminInfo?userName=`+admin.userName,{
              headers: {
                //'Content-Type': 'application/json'
              }
            }).then(res => {
              if (res.data.code === 200)
                this.$message.success("删除管理员用户成功！");
              else if (res.data.code === 100)
                this.$message.error("删除管理员用户失败！");
              //刷新宿管列表
              this.getUserList();
            }).catch(err => {
              return this.$message.warning("异常错误！" + err)
            })
          }


        }

      }
    }
</script>

<style scoped>

</style>
